<template>
  <div class="page-container" style="min-width: 1170px;">

    <el-form ref="form" :model="form" :rules="rules" :label-width="$globalCss.formLabelWidth_default"
      class="common-form-panel-div flex_cell flex_col">
      <ex_header_spiler :title="$tt('label_base_info')"></ex_header_spiler>

      <el-row>
        <el-col>
          <el-form-item :label="$tt('label_reorg_type')" prop="type">
            <ex_select_auto type="select" enum="ReorgOrderTypeEnum" class="w_fill" v-model="form.type" />
          </el-form-item>
        </el-col>
        <el-col>
          <el-form-item :label="$tt('label_stock_type')" prop="bizType">
            <ex_select_auto type="select" enum="BizTypeEnum" class="w_fill" :value="form.bizType"
              @change="changeBizType" />
          </el-form-item>
        </el-col>
        <el-col>
          <el-form-item :label="$tt('label_remark')" prop="remark">
            <ex_super_input v-model="form.remark" />
          </el-form-item>
        </el-col>
      </el-row>
      <ex_header_spiler :title="$tt('label_tms_waybill_task_view')">
        <template v-slot:left>
          <el-button type="primary" @click="addLine">{{ $tt('label_add') }}</el-button>
        </template>
      </ex_header_spiler>
      <ex_super_table v-bind="tableOption" :data="form.detailList">
      </ex_super_table>
      <el-form-item label-width="0" prop="detailList">
      </el-form-item>
      <el-form-item label-width="0">
        <span>
          <el-button type="primary" @click="submit">{{ $tt('label_save') }}</el-button>
          <el-button @click="return_page_back">{{ $tt('label_cancel') }}</el-button>
        </span>
      </el-form-item>
    </el-form>

    <stockContainerQuery_wms ref="stockContainerQuery_wms" @afterSubmit="afterSubmitTask"></stockContainerQuery_wms>
  </div>
</template>



<script>
import stockContainerQuery_wms from './dialog/stockContainerQuery_wms'
import router_params from '@/mixin/router_params';
let _default_form = {
  reorgCreateClient: 'PC',
  type: 'QUALITY_QUESTION',
  bizType: "TOC",
  remark: '',
  total: 0,
  detailList: []
}
export default {
  name: "reorg_create",
  title: 'title_reorg_create',
  mixins: [router_params],
  components: { stockContainerQuery_wms },
  data() {
    return {
      rules: {
        type: [{ required: true, message: this.$tt('tip_can_no_empty'), trigger: 'blur' }],
      },
      form: _.cloneDeep(_default_form),

      tableOption: {
        autoFlex: true,
        model: [
          {
            key: 'srcLocationCode', label: 'label_source_location', 'min-width': 120,
          },
          { key: 'srcContainerCode', label: 'label_source_container', 'min-width': 100, if: false, },
          { key: 'srcCompartmentCode', label: () => this.TOB ? this.$t('label_box_code') : this.$t('label_source_container_grid'), 'min-width': 120, },


          { key: 'skuOnlyCode', label: 'label_sku_only_code', 'width': 120, },
          {
            key: 'skuName', label: 'label_sku_info', 'width': 130, 'show-overflow-tooltip': true,
            formatter: (r, c, v, i) => this.$formatNameCode(v, r.skuNameEn)
          },
          { key: 'customerName', label: 'label_customer_name', 'width': 100, 'show-overflow-tooltip': true, },
          {
            key: 'stockNum', label: 'label_stock_sku_count', 'width': 100, 'show-overflow-tooltip': true,
            // formatter: (r, c, v, i) => v
          },
          {
            key: 'targetLocationCode', label: 'label_target_location', 'min-width': 140,
            renderHeader: (h, { column, $index }) => (<span class="table-require">{column.label}</span>),
            render: (h, { row, index }) => {
              return (
                <el-form-item
                  label-width="0px"
                  prop={`detailList.${index}.targetList`}
                  rules={this.rules.targetLocationCode}
                >
                  {
                    row.targetList.map((item, index) => {
                      return (
                        <base_location_select value={item.targetLocationCode} onInput={e => this.$set(item, 'targetLocationCode', e)}
                          class="w_fill"
                          checkArea={false} option={{ label: 'labelStr', value: 'code' }} />
                      )
                    })
                  }
                </el-form-item>
              )
            }
          },
          {
            key: 'targetContainerCode', label: 'label_target_container', 'min-width': 140, if: false,//slot: 'targetContainerCode' 
            render: (h, { row, index }) => {
              return (<el-form-item
                label-width="0px"
              >
                {
                  row.targetList.map((item, index) => {
                    return (
                      <ex_super_input value={item.targetContainerCode}
                        class="w_fill"
                        onInput={e => this.$set(item, 'targetContainerCode', e)}
                      />
                    )
                  })
                }
              </el-form-item>)
            }
          },
          {
            key: 'targetCompartmentCode', label: 'label_target_container_grid', 'min-width': 140, //slot: 'targetCompartmentCode'
            if: false,
            render: (h, { row }) => {
              return (<el-form-item
                label-width="0px"
              >
                {
                  row.targetList.map((item, index) => {
                    return (
                      <ex_super_input value={item.targetCompartmentCode} onInput={e => this.$set(item, 'targetCompartmentCode', e)}
                      />
                    )
                  })
                }
              </el-form-item>)
            }
          },
          {
            key: 'planMoveNum', label: 'label_move_count', 'min-width': 130, //slot: 'planMoveNum'
            render: (h, { row, index }) => {
              if (this.TOB) return this.$t('label_full_box_move')
              return (<el-form-item
                label-width="0px"
                prop={`detailList.${index}`}
                rules={this.rules.planMoveNum}
              >
                {
                  row.targetList.map((item, index) => {
                    return (
                      <el-input-number value={item.planMoveNum} onInput={e => this.$set(item, 'planMoveNum', e)}
                        class="w_fill"
                        max={row.stockNum} min={0}
                      />
                    )
                  })
                }
              </el-form-item>)
            }
          },
          {
            type: 'operate', width: 140, operate: [
              {
                label: 'label_split', if: (row) => !this.TOB, click: (row, i, list) => {
                  row.targetList.push({
                    targetLocationCode: "",
                    targetContainerCode: "",
                    targetCompartmentCode: "",
                    planMoveNum: 0,
                  })
                }
              },
              {
                label: 'label_remove', class: 'button_text_warning', if: (row) => row.targetList.length > 1, click: (row, i, list) => {
                  row.targetList.pop()
                }
              },
              {
                label: 'label_delete', class: 'button_text_danger', click: (row, i, list) => list.splice(i, 1)
              }
            ]
          }
        ]
      },
      rules: {
        type: { message: this.$tt('tip_can_no_empty'), type: "string", required: true },
        bizType: { message: this.$tt('tip_can_no_empty'), type: "string", required: true },
        detailList: { message: this.$tt('tip_can_no_empty'), type: "array", required: true },
        targetLocationCode: {
          type: 'array', required: true,
          defaultField: {
            type: "object", required: true,
            fields: {
              targetLocationCode: { message: this.$tt('tip_can_no_empty'), type: "string", required: true }
            },
          },
        },
        planMoveNum: {
          required: true,
          validator: (r, v, cb) => {
            if (v.targetList.some(item => !item.planMoveNum > 0)) {
              cb(this.$tt('tip_can_no_empty'))
            }
            const sum = _.reduce(v.targetList, (r, item) => r + item.planMoveNum, 0)
            sum > v.stockNum ? cb(this.$tt('tip_no_more_any', { type: this.$tt("label_usable_count") })) : cb()
          }
        },


      },
    }
  },
  computed: {

    TOB() {
      return this.form.bizType == 'TOB'
    },

  },
  methods: {
    changeBizType(e) {
      if (_.isEmpty(this.form.detailList)) {
        this.form.bizType = e
      } else {
        this.$confirm(this.$t('tip_modify_business_type_clear_detail'), this.$t('label_tip'), {
          type: 'warning'
        }).then(() => {
          this.form.bizType = e
          this.form.detailList = []
        }).catch(() => {

        });
      }
    },
    addLine() {
      if (!this.form.bizType) return this.$message.error(this.$tt('tip_please_select_first_type', { type: "label_stock_type" }))
      this.$refs.stockContainerQuery_wms.show(this.form)
    },
    afterSubmitTask(e) {
      const detailList = _.cloneDeep(this.form.detailList)
      e.forEach(it => {
        if (!detailList.some(item => `${it.skuId}.${it.locationCode}.${it.ContainerCode}.${it.subContainerCode}` ==
          `${item.skuId}.${item.srcLocationCode}.${item.srcContainerCode}.${item.srcCompartmentCode}`)) {
          // const id = `${it.skuId}.${it.locationCode}.${it.ContainerCode}.${it.subContainerCode}`
          detailList.push({
            // id: it.id,
            // sourceContainerStockId: it.id,
            srcLocationCode: it.locationCode,
            srcContainerCode: it.ContainerCode,
            srcCompartmentCode: it.subContainerCode,
            bizType: it.bizType,
            skuBarcode: it.skuBarcode,
            skuOnlyCode: it.skuOnlyCode,
            skuName: it.skuName,
            skuNameEn: it.skuNameEn,
            skuId: it.skuId,
            stockNum: it.usableQty,
            customerId: it.customerId,
            customerCode: it.customerCode,
            customerName: it.customerName,
            targetList: [
              {
                targetLocationCode: "",
                targetContainerCode: "",
                targetCompartmentCode: this.TOB ? it.subContainerCode : "",
                planMoveNum: this.TOB ? it.usableQty : 0,
              }
            ],
          })
        }
      })
      this.form.detailList = detailList
      // this.$refs.form.set("detailList", detailList)
    },
    submit() {
      if (this.$clickFast()) return
      this.$refs['form'].validate((valid, obj) => {
        if (valid) {
          let data = _.cloneDeep(this.form)
          data.detailList = _.flatMap(data.detailList, it => {
            const { targetList, ...other } = it
            return targetList.map(target => {
              return {
                ...other,
                ...target,
              }
            })
          })
          data.totalNum = _.reduce(data.detailList, (r, v) => r + v.planMoveNum, 0)
          this.$ajax({
            url: "/wms-api/inside/ReorgOrderRpc/create.json",
            type: 'json', loading: true,
            method: 'post',
            data,
            success: (res) => {
              this.$message.success(this.$tt('tip_submit_success'))
              this.return_emit(null, "reload")
              this.return_page_back()
            },
          })
        } else {
          this.$message.error(this.$tt('form_validate_error'))
          return false;
        }
      });
    },
  }

}
</script>

<style scoped></style>
